package com.farm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.farm.pojo.User;
import com.farm.mapper.UserMapper;
import com.farm.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.AppHttpCodeEnum;
import com.heima.common.exception.ResponseResult;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author farm
 * @since 2023-10-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResponseResult userLogin(User user) {
        System.out.println(user);
        if(StringUtils.isNotBlank(user.getUsername()) && StringUtils.isNotBlank(user.getPassword())){
            User dbUser = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
            if(dbUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户信息不存在");
            }
            String salt = dbUser.getSalt();
            String password = user.getPassword();
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!pswd.equals(dbUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            String token = AppJwtUtil.getToken(dbUser.getUserId().longValue());
            Map<String,Object> map =new HashMap<>();
            map.put("token",token);
            dbUser.setSalt("");
            dbUser.setPassword("");
            map.put("user",dbUser);
            return ResponseResult.okResult(map);
        }else {
            //游客登录
//            Map<String,Object> map =new HashMap<>();
//            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.errorResult(0,"没有该用户名");
        }
    }

    @Override
    public ResponseResult getUserInfo(User user) {
        String username = user.getUsername();
        User one = getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
        if(one == null){
            return ResponseResult.errorResult(0,"业务繁忙");
        }
        one.setUserId(0L);
        one.setPassword("0");
        one.setSalt("0");
        return ResponseResult.okResult(one);
    }
}
